#include "Coordinator2D.h"


Coordinator2D::Coordinator2D(void)
{
	this->X0 = 0;
	this->Y0 = 0;
	this->dx = 1.0f;
	this->dy = 1.0f;
	this->kx = this->ky = .1f;
	this->n = 0;
	this->step = 5;

	penX = CreatePen(PS_SOLID, 2, RGB(255, 0, 255));
	penY = CreatePen(PS_SOLID, 2, RGB(0, 0, 255));
	dataPen = CreatePen(PS_SOLID, 2, RGB(10, 200, 25));
}

Coordinator2D::Coordinator2D(int x0, int y0, COLORREF clx, COLORREF cly, float lx, float ly)
{
	this->X0 = x0;
	this->Y0 = y0;
	this->dx = lx;
	this->dy = ly;
	this->colorX = clx;
	this->colorY = cly;
	this->kx = this->ky = .1f;
	this->n = 0;
	this->step = 5;

	penX = CreatePen(PS_SOLID, 2, RGB(255, 0, 255));
	penY = CreatePen(PS_SOLID, 2, RGB(0, 0, 255));
	dataPen = CreatePen(PS_SOLID, 2, RGB(10, 200, 25));
}

Coordinator2D::~Coordinator2D(void)
{
	DeleteObject(penX);
	DeleteObject(penY);
	DeleteObject(dataPen);
}

void Coordinator2D::setScale(float sclx, float scly)
{
	this->kx = sclx;
	this->ky = scly;
}

void Coordinator2D::setViewport(int l, int t, int r, int b)
{
	this->left = l;
	this->top = t;
	this->right = r;
	this->bottom = b;

	//this->step = 5;
	//this->n = (r - l)/step;
	maxN = (right - left)/step;
}

void Coordinator2D::moveTo(int x0, int y0)
{
	this->X0 = x0;
	this->Y0 = y0;
}

void Coordinator2D::draw(HDC hdc)
{
	int i;
	RECT clientRect;
	HBRUSH bgbrush, oldBrush;
	clientRect.left = left;
	clientRect.top = top;
	clientRect.right = right;
	clientRect.bottom = bottom;
	if(n >= maxN){
		bgbrush = CreateSolidBrush(RGB(0, 0, 0));
		oldBrush = (HBRUSH)SelectObject(hdc, bgbrush);
		FillRect(hdc, &clientRect, bgbrush);
	}

	MoveToEx(hdc, this->left, this->Y0, NULL);
	HPEN oldPen = (HPEN) SelectObject(hdc, penX);
	LineTo(hdc, this->right, this->Y0);

	MoveToEx(hdc, this->X0, this->top, NULL);
	SelectObject(hdc, penY);
	LineTo(hdc, this->X0, this->bottom);
	SelectObject(hdc, dataPen);
	
	if(n>0){
		MoveToEx(hdc, this->X0, data[0], NULL);
		for(i = 1; i<n; i++)
			LineTo(hdc, this->X0 + i * step, data[i]);
	}

	SelectObject(hdc, oldPen);
}

int Coordinator2D::world2Screen(float value){
	//in this case, value hold the y value
	return (Y0 - value/ky);
}

void Coordinator2D::addValue(float val){
	int scval = world2Screen(val);
	int i;
	if(n < maxN){
		data[n] = scval;
		n++;
	}else{
		for(i=0;i<n-1;i++)
			data[i] = data[i+1];
		data[n-1] = scval;
	}
}

/*
	World to screen
	x_screen = X0 + x/kx;
	y_screen = Y0 - y/ky;

*/